<?php
namespace Asset\Controller;
use Common\Controller\AdminbaseController;
class StoreController extends AdminbaseController {
	protected $device_model,$susers_model,$region_model;
	function _initialize() {
		parent::_initialize();
		$this->store_model = D("Store");
		$this->device_model = D("Device");
		$this->susers_model = D("Susers");
		$this->region_model = D("Region");
        $this->backup_path = '/data/';
	}
    private function devicestatus() {
		$devicestatus =
		array(
			array(
		        'ALL' => array('name' => '请选择'),
		        'ZX' => array('id' => 'ZX','name' => '二代保温箱'),
		        'MX' => array('id' => 'MX','name' => '三代保温箱'),
		        'FX' => array('id' => 'FX','name' => '四代保温箱'),
		        'AD' => array('id' => 'AD','name' => '广告机'),
		        'TA' => array('id' => 'TA','name' => '游戏桌'),
		        'OS' => array('id' => 'OS','name' => '外置摇一摇'),
		        'CS' => array('id' => 'CS','name' => '影院摇一摇'),
		        'CM' => array('id' => 'CM','name' => '自动咖啡机'),
		        'GK' => array('id' => 'GK','name' => '工卡'),
		        'QT' => array('id' => 'QT','name' => '其他设备')
	        ),
	        array(
	            '0'=>array('id' => '0', 'name'=>'请选择'),
	            '1'=>array('id' => '1', 'name'=>'停用'),
	            '2'=>array('id' => '2', 'name'=>'激活'),
	            '3'=>array('id' => '3', 'name'=>'损坏'),
	            '4'=>array('id' => '4', 'name'=>'发货'),
	            '5'=>array('id' => '5', 'name'=>'入库'),
	            '6'=>array('id' => '6', 'name'=>'出场'),
	        ),
	        array(
	            '0'=>array('id' => '0', 'name'=>'请选择'),
	            '1'=>array('id' => '1', 'name'=>'店铺名称'),
	            '2'=>array('id' => '2', 'name'=>'子名称'),
	            '3'=>array('id' => '3', 'name'=>'店铺地址'),
	            '4'=>array('id' => '4', 'name'=>'省市区'),
	        ),
	        array(
				'0'=>array('name'=>'请选择'),
				'100'=>array('id'=>'100','name'=>'电影院'),
				'105'=>array('id'=>'105','name'=>'私人影吧'),
				'110'=>array('id'=>'110','name'=>'奶茶/水吧'),
				'120'=>array('id'=>'120','name'=>'商超'),
				'125'=>array('id'=>'125','name'=>'KTV'),
				'130'=>array('id'=>'130','name'=>'便利店'),
				'135'=>array('id'=>'135','name'=>'烘培蛋糕店'),
				'140'=>array('id'=>'140','name'=>'西餐厅/中餐厅'),
				'150'=>array('id'=>'150','name'=>'咖啡/甜品店'),
				'160'=>array('id'=>'160','name'=>'酒吧/夜店'),
				'170'=>array('id'=>'170','name'=>'小吃店/零食店'),
				'180'=>array('id'=>'180','name'=>'网咖/网吧'),
				'190'=>array('id'=>'190','name'=>'主题公园/景区'),
				'200'=>array('id'=>'200','name'=>'副食品店'),
				'500'=>array('id'=>'500','name'=>'其他'),
			),
	        array(
	            '0'=>array('id' => '0', 'name'=>'请选择'),
	            '1'=>array('id' => '1', 'name'=>'删除'),
	            '2'=>array('id' => '2', 'name'=>'试营'),
	            '3'=>array('id' => '3', 'name'=>'正常'),
	            '4'=>array('id' => '4', 'name'=>'暂停'),
	            '5'=>array('id' => '5', 'name'=>'解约'),
	            '6'=>array('id' => '6', 'name'=>'草稿'),
	        ),
		);
		return $devicestatus;
    }
	function index(){
		$this->_lists();
		$this->display();
	}
	function _lists(){
		if(I('param.')){
			$keyword =I('param.keyword');
			if(I('param.search') ==1){$search[] = array('title'=>array('like',"%$keyword%"));}
			if(I('param.search') ==2){$search[] = array('title_branch'=>array('like',"%$keyword%"));}
			if(I('param.search') ==3){$search[] = array('address'=>array('like',"%$keyword%"));}
            if(I('param.stype')){
            	$stype =I('param.stype');
                $search[] = array('stype'=>$stype);
            }
            if(I('param.start_time')){
                    $search[] = array('date(updatetime)'=>array('egt',I('param.start_time')));
            }
            if(I('param.end_time')){
                    $search[] = array('date(updatetime)'=>array('elt',I('param.end_time')));
            }
            $_GET['stype'] = I('param.stype');
			$_GET['search']=I('param.search');
			$_GET['keyword']=I('param.keyword');
            $_GET['start_time'] = I('param.start_time');
            $_GET['end_time'] = I('param.end_time');
		}

		$count=$this->store_model->where($search)->count();
		$page = $this->page($count,50);
		$stores=$this->store_model->where($search)
		->limit($page->firstRow . ',' . $page->listRows)
		->order("id DESC")->select();
		$bstatus = $this->devicestatus();
		$this->assign("stype", $bstatus[3]);
		$this->assign("search", $bstatus[2]);
		$this->assign("status", $bstatus[4]);
    	$this->assign('page', $page->show('Admin'));
		$this->assign("stores", $stores);
		$this->assign("count", $count);
	}
	public function edit(){
		$store = $this->store_model->where(array('id'=>I("get.id")))->find();
		$devices = $this->device_model->where(array('store_id'=>$store['store_id']))->select();
		$oid[0]=$store['user_id'];
		$oid[1]=$store['owner_id'];
		$oid[2]=$store['agency_id'];
		$oid[3]=$store['marketing_id'];
		$oid[4]=$store['sign_user_id'];
		$susers = $this->susers_model->where(array('oid'=>array('in',$oid)))->select();
		$code[0]=$store['province_id'];
		$code[1]=$store['city_id'];
		$code[2]=$store['district_id'];
		$region = $this->region_model->where(array('code'=>array('in',$code)))->select();
		$bstatus = $this->devicestatus();
		$this->assign("store", $store);
		$this->assign("devices", $devices);
		$this->assign("susers", $susers);
		$this->assign("region", $region);
		$this->assign("btype", $bstatus[0]);
		$this->assign("bstatus", $bstatus[1]);
		$this->assign("stype", $bstatus[3]);
		$this->assign("urlimg", C('IMG_PATH'));
		$this->display();
	}
	public function loding_post(){
		if(IS_POST){
			if(empty(I('post.devid'))){
	    		$this->error('请选择设备');
			}
			foreach(I('post.devid') as $devid){
    			$loding = $this->device_model->where(array('id'=>$devid))->find();
				if($loding['loding']){
					$this->device_model->where(array('id'=>$devid))->setField('loding','');
					if(!$this->device_model->where(array('loding'=>$loding['loding']))->find()){
						$Aliyun = new \Aliyun\Controller\AliyunController();
						$Aliyun->delete($loding['loding']);
	    			}
				}
			}
			if($_FILES){
				$Aliyun = new \Aliyun\Controller\AliyunController();
				$loding_img = $Aliyun->save($_FILES["loding_img"],'img/'.CONTROLLER_NAME);
				if(!$loding_img['error']){
					$_POST['loding'] =$loding_img['path'].$loding_img['name'];
				}else{
					$this->error('图像上传失败');
				}
			}else{
					$this->error('请上传图像');
			}
			if($this->device_model->where(array('id'=>array('in',I('post.devid'))))->save($_POST)){
				$this->success("添加成功！");
			} else {
				$this->error("添加失败！");
			}
		}
	}
	public function remove(){
    	if (I("get.id")) {
    		$device = $this->device_model->where(array('id'=>I("get.id")))->find();
    		if ($this->device_model->where(array('id'=>I("get.id")))->setField(array('status'=>'1','store_id'=>'0','loding'=>''))) {
    			if(!$this->device_model->where(array('loding'=>$device['loding']))->find()){
					$Aliyun = new \Aliyun\Controller\AliyunController();
					$Aliyun->delete($device['loding']);
    			}
    			$this->success("设备解绑成功！");
    		} else {
    			$this->error('设备解绑失败！');
    		}
    	} else {
			$this->error($this->device_model->getError());
    	}
	}
	public function remove_loding(){
    	if (I("get.id")) {
    		$device = $this->device_model->where(array('id'=>I("get.id")))->find();
    		if ($this->device_model->where(array('id'=>I("get.id")))->setField('loding','')) {
    			if(!$this->device_model->where(array('loding'=>$device['loding']))->find()){
					$Aliyun = new \Aliyun\Controller\AliyunController();
					$Aliyun->delete($device['loding']);
    			}
    			$this->success("Loding图移除成功！");
    		} else {
    			$this->error('Loding图移除失败！');
    		}
    	} else {
			$this->error($this->device_model->getError());
    	}
	}
	public function edit_post(){
		if (IS_POST) {
			if(!I("post.title")){
				$this->error("必须输入店铺名称");
			}
			if ($this->store_model->where(array('id'=>I("post.sid")))->save($_POST)) {
				$this->success("更新成功！",U('Store/index'));
			} else {
				$this->error("更新失败！");
			}
		}
	}

    public function download(){
        $backup_name = isset($_GET['backup']) && trim($_GET['backup']) ? trim($_GET['backup']) :
            $this->error('请选择文件名称！');
        $file = isset($_GET['file']) && trim($_GET['file']) ? trim($_GET['file']) : $this->
            error('请选择文件文件！');
        $sql_file = SITE_PATH . $this->backup_path . $backup_name . '/' . $file;
        if (file_exists($sql_file)){
            header('Content-type: application/unknown');
            header('Content-Disposition: attachment; filename="' . $file . '"');
            header("Content-Length: " . filesize($sql_file) . "; ");
            readfile($sql_file);
        }else{
            $this->error('文件不存在！');
        }
    }
	public function export_csv($filename, $data){
		$file_hwnd=fopen('data/runtime/'.$filename,"w");
		header("Content-type:text/csv");
		header("Content-Disposition:attachment;filename=".$filename);
		header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
		header('Expires:0');
		header('Pragma:public');
		fwrite($file_hwnd,$data);
		fclose($file_hwnd);
	}
    public function outcsv(){
		if(I('param.')){
			$keyword =I('param.keyword');
			if(I('param.search') ==1){$search[] = array('barcode'=>array('like',"%$keyword%"));}
			if(I('param.search') ==2){$search[] = array('devid'=>array('like',"%$keyword%"));}
			if(I('param.search') ==3){$search[] = array('uuid'=>array('like',"%$keyword%"));}
			if(I('param.search') ==4){$search[] = array('major'=>array('like',"%$keyword%"));}
			if(I('param.search') ==5){$search[] = array('minor'=>array('like',"%$keyword%"));}
            if(I('param.btype')){
            	$btype =I('param.btype');
                $search[] = array('btype'=>$btype);
            }
            if(I('param.status')){
        		$status =I('param.status');
                $search[] = array('status'=>$status);
            }
            if(I('param.start_time')){
                    $search[] = array('date(updatetime)'=>array('egt',I('param.start_time')));
            }
            if(I('param.end_time')){
                    $search[] = array('date(updatetime)'=>array('elt',I('param.end_time')));
            }
		}
		if(!I('param.btype') && !I('param.status') && !I('param.search') && !I('param.keyword') && !I('param.start_time') && !I('param.end_time')){
		    $this->error('请选择查询条件！');
		}
		$device=$this->device_model->where($search)->select();
		if(count($device) > 20000){
			$this->error('导出数据过多会导致内存溢出！请分别查询导出！');
		}
		$bstatus = $this->devicestatus();
		$head[] = iconv('utf-8','GBK',",SN码,设备ID,UUID,Major,Minor,店铺名称,店铺子名称,店铺地址,店铺类型,省,市,区\r\n");
		if($device){
			set_time_limit(0);
			foreach($device as $dev){
				$store = $this->store_model->where(array('store_id'=>$dev['store_id']))->find();
				if($store['province_id'] && $store['city_id'] && $store['district_id']){
					$province = $this->region_model->where(array('code'=>$store['province_id']))->find();
					$city = $this->region_model->where(array('code'=>$store['city_id']))->find();
					$district = $this->region_model->where(array('code'=>$store['district_id']))->find();
				}else{
					$province['name'] = '中国';
					$city['name'] = '';
					$district['name'] = '';
				}
				$content[] = iconv('utf-8','GBK',$dev['barcode']).",".
						iconv('utf-8','GBK',$dev['devid']).",".
						iconv('utf-8','GBK',$dev['uuid']).",".
						iconv('utf-8','GBK',$dev['major']).",".
						iconv('utf-8','GBK',$dev['minor']).",".
						iconv('utf-8','GBK',$store['title']).",".
						iconv('utf-8','GBK',$store['title_branch']).",".
						iconv('utf-8','GBK',$store['address']).",".
						iconv('utf-8','GBK',$bstatus[3][$store['stype']]['name']).",".
						iconv('utf-8','GBK',$province['name']).",".
						iconv('utf-8','GBK',$city['name']).",".
						iconv('utf-8','GBK',$district['name'])."\r\n";
			}
		}
		$csvname =time().'.csv';
		$str = implode(',',array_merge($head, $content));
		$this->export_csv($csvname,$str);
		$this->success('导出完成',U('Store/download', array('backup'=>'runtime', 'file'=>"$csvname")));
    }
}
